import { useSession, signOut } from 'next-auth/react';
import Link from 'next/link';
import Script from 'next/script';
import { useState, useRef, useEffect } from 'react';
import { useTheme } from 'next-themes';

// 菜单数据结构
const menuItems = [
  {
    title: '首页',
    href: '/',
    icon: '🏠'
  },
  {
    title: '历史版本',
    href: '/docs',
    icon: '📚',
    children: [
      {
        title: '1.0大模型直接回复',
        href: '/docs/1.0',
        icon: '🤖'
      },
      {
        title: '2.0网格搜索最优参数',
        href: '/docs/2.0',
        icon: '🔍'
      },
      {
        title: '3.0快速随机搜索最优参数',
        href: '/docs/3.0',
        icon: '🎲'
      },
      {
        title: '4.0规则参数交易模型',
        href: '/docs/4.0',
        icon: '🎯'
      },
      {
        title: '5.0深度强化学习交易模型',
        href: '/docs/5.0',
        icon: '🧠'
      }
    ]
  },
  {
    title: '综合',
    href: '/system',
    icon: '⚙️',
    children: [
      {
        title: '环境工具',
        href: '/system/users',
        icon: '👥'
      },
      {
        title: '常用平台',
        href: '/system/roles',
        icon: '🔑'
      },
      {
        title: '联系我们',
        href: '/system/settings/basic',
        icon: '⚡'
      },
      {
        title: '安全设置',
        href: '/system/settings/security',
        icon: '🔒'
      }
    ]
  }
/*   {
    title: '内容管理',
    icon: '📝',
    children: [
      {
        title: '文章管理',
        href: '/content/articles',
        children: [
          { title: '文章列表', href: '/content/articles/list' },
          { title: '分类管理', href: '/content/articles/categories' }
        ]
      }
    ]
  } */
];

// 下拉菜单组件
const DropdownMenu = ({ item, level = 0 }) => {
  const hasChildren = item.children && item.children.length > 0;
  const [menuOffset, setMenuOffset] = useState(0);
  const [isVisible, setIsVisible] = useState(false);
  const menuRef = useRef(null);
  const timeoutRef = useRef(null);

  const handleMouseEnter = () => {
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
    }
    setIsVisible(true);
  };

  const handleMouseLeave = () => {
    timeoutRef.current = setTimeout(() => {
      setIsVisible(false);
    }, 500);
  };

  useEffect(() => {
    return () => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
    };
  }, []);

  useEffect(() => {
    const handleScroll = () => {
      if (menuRef.current && level > 0) {
        const menuRect = menuRef.current.getBoundingClientRect();
        const footerTop = document.querySelector('footer')?.getBoundingClientRect().top || 0;
        const viewportHeight = window.innerHeight;
        
        if (menuRect.bottom > footerTop) {
          const offset = menuRect.bottom - footerTop;
          setMenuOffset(offset);
        } else {
          setMenuOffset(0);
        }
      }
    };

    window.addEventListener('scroll', handleScroll);
    window.addEventListener('resize', handleScroll);
    
    handleScroll();

    return () => {
      window.removeEventListener('scroll', handleScroll);
      window.removeEventListener('resize', handleScroll);
    };
  }, [level]);

  return (
    <div 
      className="relative group"
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
    >
      {hasChildren ? (
        <>
          <button
            className={`flex items-center text-sm font-medium text-gray-700 dark:text-gray-300 hover:text-blue-600 dark:hover:text-blue-400 hover:bg-gray-50 dark:hover:bg-gray-800 ${
              level === 0 
                ? 'px-6 h-16 min-w-[160px] border-b-2 border-transparent hover:border-blue-500 hover:bg-blue-50 dark:hover:bg-gray-800 justify-center' 
                : 'w-full px-4 py-2 hover:bg-blue-50 dark:hover:bg-gray-800'
            }`}
          >
            {level === 0 ? (
              <div className="flex items-center justify-center space-x-2">
                <span className="flex-shrink-0">{item.icon}</span>
                <span className="whitespace-nowrap">{item.title}</span>
                <svg
                  className={`w-4 h-4 transform ${isVisible ? 'rotate-180' : ''} flex-shrink-0`}
                  style={{ transition: isVisible ? 'transform 0s' : 'transform 0.2s ease-in-out' }}
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                </svg>
              </div>
            ) : (
              <>
                <span className="mr-2 flex-shrink-0">{item.icon}</span>
                <span className="flex-1 text-left whitespace-nowrap">{item.title}</span>
                <svg
                  className={`w-4 h-4 transform ${isVisible ? 'rotate-180' : ''} flex-shrink-0`}
                  style={{ transition: isVisible ? 'transform 0s' : 'transform 0.2s ease-in-out' }}
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                </svg>
              </>
            )}
          </button>
          <div
            ref={menuRef}
            style={{ 
              transform: menuOffset > 0 ? `translateY(-${menuOffset}px)` : 'none',
              transition: isVisible 
                ? 'transform 0.2s ease-in-out, opacity 0s, visibility 0s' 
                : 'transform 0.2s ease-in-out, opacity 0.5s ease-in-out, visibility 0.5s ease-in-out'
            }}
            className={`absolute bg-white dark:bg-[rgb(28,31,38)] rounded-lg shadow-lg py-1 ${isVisible ? 'opacity-100 visible' : 'opacity-0 invisible'} border border-gray-100 dark:border-gray-700 z-50 ${
              level === 0 
                ? 'min-w-[160px] left-0 top-full mt-0.5' 
                : 'min-w-[160px] left-full top-0 ml-0.5'
            }`}
          >
            {item.children.map((child, index) => (
              <div key={index} className="w-full bg-white dark:bg-[rgb(28,31,38)] transition-colors duration-200">
                <DropdownMenu item={child} level={level + 1} />
              </div>
            ))}
          </div>
        </>
      ) : (
        <Link
          href={item.href}
          className={`flex items-center text-sm text-gray-700 dark:text-gray-300 hover:text-blue-600 dark:hover:text-blue-400 hover:bg-blue-50 dark:hover:bg-gray-800 ${
            level === 0 
              ? 'px-6 h-16 min-w-[160px] border-b-2 border-transparent hover:border-blue-500 justify-center' 
              : 'w-full px-4 py-2'
          }`}
        >
          {level === 0 ? (
            <div className="flex items-center justify-center space-x-2">
              <span className="flex-shrink-0">{item.icon}</span>
              <span className="whitespace-nowrap">{item.title}</span>
            </div>
          ) : (
            <>
              <span className="mr-2 flex-shrink-0">{item.icon}</span>
              <span className="flex-1 text-left whitespace-nowrap">{item.title}</span>
            </>
          )}
        </Link>
      )}
    </div>
  );
};

export default function Layout({ children, documentMenu }) {
  const { data: session } = useSession();
  const { theme, setTheme, resolvedTheme } = useTheme();
  const [mounted, setMounted] = useState(false);
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);

  useEffect(() => {
    setMounted(true);
  }, []);

  // 同步系统主题
  useEffect(() => {
    if (mounted && resolvedTheme) {
      setTheme(resolvedTheme);
    }
  }, [mounted, resolvedTheme, setTheme]);

  const handleSignOut = async () => {
    try {
      // 获取当前域名
      const currentUrl = window.location.origin;
      console.log('Signing out, current URL:', currentUrl);
      
      await signOut({ 
        callbackUrl: currentUrl,
        redirect: true
      });
    } catch (error) {
      console.error('Sign out error:', error);
    }
  };

  // 移动端菜单项组件
  const MobileMenuItem = ({ item, level = 0, onClose }) => {
    const [isOpen, setIsOpen] = useState(true);
    const hasChildren = item.children && item.children.length > 0;

    return (
      <div className="w-full">
        {hasChildren ? (
          <>
            <button
              onClick={() => setIsOpen(!isOpen)}
              className="w-full flex items-center text-sm text-gray-700 dark:text-gray-300 hover:text-blue-600 dark:hover:text-blue-400 hover:bg-gray-50 dark:hover:bg-gray-800 px-4 py-3 transition-colors"
              style={{ paddingLeft: `${level * 1 + 1}rem` }}
            >
              <span className="mr-2">{item.icon}</span>
              <span className="flex-1 text-left">{item.title}</span>
              <svg
                className={`w-4 h-4 transform transition-transform duration-200 ${isOpen ? 'rotate-180' : ''}`}
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
              </svg>
            </button>
            {isOpen && (
              <div className="bg-gray-50 dark:bg-[rgb(24,27,33)]">
                {item.children.map((child, index) => (
                  <MobileMenuItem key={index} item={child} level={level + 1} onClose={onClose} />
                ))}
              </div>
            )}
          </>
        ) : (
          <Link
            href={item.href}
            onClick={onClose}
            className="w-full flex items-center text-sm text-gray-700 dark:text-gray-300 hover:text-blue-600 dark:hover:text-blue-400 hover:bg-gray-50 dark:hover:bg-gray-800 px-4 py-3 transition-colors"
            style={{ paddingLeft: `${level * 1 + 1}rem` }}
          >
            <span className="mr-2">{item.icon}</span>
            <span className="flex-1 text-left">{item.title}</span>
          </Link>
        )}
      </div>
    );
  };

  return (
    <div className="min-h-screen bg-white dark:bg-[rgb(34,37,45)] transition-colors duration-200">
      {/* 导航栏 */}
      <header className="fixed top-0 left-0 right-0 z-50 bg-gray-200 dark:bg-[rgb(18,21,27)] border-b border-gray-200 dark:border-[rgb(28,31,38)]">
        <nav className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-4">
          <div className="flex justify-between h-16">
            <div className="flex">
              {/* 移动端菜单按钮 */}
              <button
                onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
                className="sm:hidden -ml-1 mr-2 flex items-center"
              >
                <svg
                  className="w-6 h-6 text-gray-500 dark:text-gray-400"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  {isMobileMenuOpen ? (
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M6 18L18 6M6 6l12 12"
                    />
                  ) : (
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M4 6h16M4 12h16M4 18h16"
                    />
                  )}
                </svg>
              </button>

              <div className="flex-shrink-0 flex items-center">
                <Link href="/" className="text-xl font-bold hover:text-blue-600 dark:hover:text-blue-400 transition-colors">
                  <svg width="180" height="36" viewBox="0 0 220 36" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <defs>
                      <linearGradient id="logoGradient" x1="0%" y1="0%" x2="100%" y2="100%">
                        <stop offset="0%" style={{ stopColor: '#1A237E', stopOpacity: 0.98 }} />
                        <stop offset="25%" style={{ stopColor: '#0D47A1', stopOpacity: 0.98 }} />
                        <stop offset="50%" style={{ stopColor: '#1565C0', stopOpacity: 0.98 }} />
                        <stop offset="75%" style={{ stopColor: '#1976D2', stopOpacity: 0.98 }} />
                        <stop offset="100%" style={{ stopColor: '#2196F3', stopOpacity: 0.98 }} />
                      </linearGradient>
                      <filter id="glow">
                        <feGaussianBlur stdDeviation="0.3" result="coloredBlur"/>
                        <feFlood floodColor="#2196F3" floodOpacity="0.15" result="glowColor"/>
                        <feComposite in="glowColor" in2="coloredBlur" operator="in" result="softGlow"/>
                        <feMerge>
                          <feMergeNode in="softGlow"/>
                          <feMergeNode in="SourceGraphic"/>
                        </feMerge>
                      </filter>
                      <filter id="shadow">
                        <feDropShadow dx="0" dy="0.5" stdDeviation="0.8" floodColor="#000" floodOpacity="0.15"/>
                      </filter>
                      <style>
                        {`
                          .logo-text {
                            transition: transform 0.3s ease-out, filter 0.3s ease-out;
                            transform-origin: center;
                            letter-spacing: 0.8px;
                            text-shadow: 0 1px 2px rgba(0,0,0,0.08);
                          }
                          .logo-text:hover {
                            transform: translateY(-1px);
                            filter: brightness(1.1);
                          }
                          .logo-text .highlight {
                            font-weight: 700;
                            background: linear-gradient(120deg, #2196F3, #1976D2);
                            -webkit-background-clip: text;
                            -webkit-text-fill-color: transparent;
                            background-clip: text;
                          }
                        `}
                      </style>
                    </defs>
                    {/* 主文本 */}
                    <text x="8" y="28" fontFamily="'PingFang SC', 'Microsoft YaHei', Arial, sans-serif" fontSize="26" fontWeight="600" fill="url(#logoGradient)" filter="url(#glow) url(#shadow)" className="logo-text">
                      <tspan className="highlight">小铭Ai梦想家</tspan>
                    </text>
                  </svg>
                </Link>
              </div>
              {/* 顶部菜单 */}
              <div className="hidden sm:ml-8 sm:flex">
                {menuItems.map((item, index) => (
                  <DropdownMenu key={index} item={item} />
                ))}
              </div>
            </div>
            <div className="flex items-center space-x-4">
              {/* 暗夜模式切换按钮 */}
              <button
                aria-label="Toggle Dark Mode"
                type="button"
                className="w-8 h-8 p-1 ml-1 mr-1 rounded-full text-gray-500 dark:text-gray-400 hover:text-blue-600 dark:hover:text-blue-400"
                onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}
              >
                {mounted && (
                  theme === 'dark' ? (
                    <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z" />
                    </svg>
                  ) : (
                    <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z" />
                    </svg>
                  )
                )}
              </button>
              {session?.user?.isAdmin ? (
                <span className="text-sm text-gray-500 dark:text-gray-400 mr-4 px-3 py-1 bg-gray-100 dark:bg-gray-800 rounded-full">
                  管理员
                </span>
              ) : null}
              {session ? (
                <button
                  onClick={handleSignOut}
                  className="text-sm text-gray-500 dark:text-gray-400 hover:text-blue-600 dark:hover:text-blue-400 transition-colors"
                >
                  退出
                </button>
              ) : null}
            </div>
          </div>
        </nav>

        {/* 移动端菜单 */}
        <div
          className={`fixed inset-0 bg-black bg-opacity-50 z-40 transition-opacity duration-300 sm:hidden ${
            isMobileMenuOpen ? 'opacity-100' : 'opacity-0 pointer-events-none'
          }`}
          onClick={() => setIsMobileMenuOpen(false)}
        />
        <div
          className={`fixed top-16 left-0 bottom-0 w-64 bg-gray-100 dark:bg-[rgb(24,27,33)] border-r border-gray-200 dark:border-gray-700 transform transition-transform duration-300 ease-in-out z-50 sm:hidden ${
            isMobileMenuOpen ? 'translate-x-0' : '-translate-x-full'
          }`}
        >
          <div className="h-full overflow-y-auto">
            <div className="py-2">
              {menuItems.map((item, index) => (
                <MobileMenuItem key={index} item={item} onClose={() => setIsMobileMenuOpen(false)} />
              ))}
              
              {/* 文档目录 */}
              {documentMenu && documentMenu.length > 0 && (
                <>
                  <div className="px-4 py-3 text-sm font-semibold text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-[rgb(24,27,33)] border-t border-b border-gray-200 dark:border-gray-700">
                    文档目录
                  </div>
                  {documentMenu.map((item, index) => (
                    <a
                      key={index}
                      href={`#${item.id}`}
                      onClick={(e) => {
                        e.preventDefault();
                        setIsMobileMenuOpen(false);
                        const element = document.getElementById(item.id);
                        if (element) {
                          const headerOffset = 80;
                          const elementPosition = element.getBoundingClientRect().top;
                          const offsetPosition = elementPosition + window.pageYOffset - headerOffset;
                          window.scrollTo({
                            top: offsetPosition,
                            behavior: 'smooth'
                          });
                        }
                      }}
                      className="block w-full text-sm text-gray-700 dark:text-gray-300 hover:text-blue-600 dark:hover:text-blue-400 hover:bg-gray-200 dark:hover:bg-[rgb(38,41,48)] px-4 py-2 transition-colors"
                      style={{ 
                        paddingLeft: `${(item.level - 1) * 1 + 1}rem`
                      }}
                    >
                      {item.text}
                    </a>
                  ))}
                </>
              )}
            </div>
          </div>
        </div>
      </header>

      {/* 主要内容区域 */}
      <main className="pt-16 min-h-[calc(100vh-330px)]">
        {children}
      </main>

      {/* 页脚 */}
      <footer className="bg-gray-200 dark:bg-[rgb(18,21,27)] border-t border-gray-300 dark:border-[rgb(28,31,38)] relative z-40 transition-colors duration-200 opacity-100 transition-opacity">
        {/* 主要内容区 */}
        <div className="max-w-7xl mx-auto py-12 px-4 sm:px-6 lg:px-8">
          <div className="grid grid-cols-1 md:grid-cols-4 gap-8">
            {/* 公司介绍 */}
            <div className="col-span-1 md:col-span-2">
              <h3 className="text-sm font-semibold text-gray-600 dark:text-gray-300 tracking-wider uppercase mb-4">
                内容说明
              </h3>
              <p className="text-base text-gray-500 dark:text-gray-400 mb-4">
              本站所有内容根据AI自动生成，仅限用于学习研究和技术交流，不构成任何投资建议。市场有风险，投资需谨慎。
              </p>
              <div className="flex space-x-6">
                <a href="#" className="text-gray-400 dark:text-gray-500 hover:text-gray-500 dark:hover:text-gray-400">
                  <span className="sr-only">Twitter</span>
                  <svg className="h-6 w-6" fill="currentColor" viewBox="0 0 24 24">
                    <path d="M8.29 20.251c7.547 0 11.675-6.253 11.675-11.675 0-.178 0-.355-.012-.53A8.348 8.348 0 0022 5.92a8.19 8.19 0 01-2.357.646 4.118 4.118 0 001.804-2.27 8.224 8.224 0 01-2.605.996 4.107 4.107 0 00-6.993 3.743 11.65 11.65 0 01-8.457-4.287 4.106 4.106 0 001.27 5.477A4.072 4.072 0 012.8 9.713v.052a4.105 4.105 0 003.292 4.022 4.095 4.095 0 01-1.853.07 4.108 4.108 0 003.834 2.85A8.233 8.233 0 012 18.407a11.616 11.616 0 006.29 1.84" />
                  </svg>
                </a>
                <a href="#" className="text-gray-400 dark:text-gray-500 hover:text-gray-500 dark:hover:text-gray-400">
                  <span className="sr-only">GitHub</span>
                  <svg className="h-6 w-6" fill="currentColor" viewBox="0 0 24 24">
                    <path fillRule="evenodd" d="M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.531 1.032 1.531 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0112 6.844c.85.004 1.705.115 2.504.337 1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.202 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.943.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.019 10.019 0 0022 12.017C22 6.484 17.522 2 12 2z" clipRule="evenodd" />
                  </svg>
                </a>
              </div>
            </div>

            {/* 快速链接 */}
            <div className="col-span-1">
              <h3 className="text-sm font-semibold text-gray-600 dark:text-gray-300 tracking-wider uppercase mb-4">
                快速链接
              </h3>
              <ul className="space-y-4">
                <li>
                  <Link href="/about" className="text-base text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-300">
                    关于我们
                  </Link>
                </li>
                <li>
                  <Link href="/contact" className="text-base text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-300">
                    联系我们
                  </Link>
                </li>
                <li>
                  <Link href="/privacy" className="text-base text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-300">
                    隐私政策
                  </Link>
                </li>
              </ul>
            </div>

            {/* 联系方式 */}
            <div className="col-span-1">
              <h3 className="text-sm font-semibold text-gray-600 dark:text-gray-300 tracking-wider uppercase mb-4">
                联系我们
              </h3>
              <ul className="space-y-4">
                <li className="text-base text-gray-500 dark:text-gray-400">
                  <span className="font-medium">邮箱：</span>
                  support@autotrad.com
                </li>
              </ul>
            </div>
          </div>
        </div>

        {/* 版权信息和备案 */}
        <div className="bg-gray-200 dark:bg-[rgb(18,21,27)] border-t border-gray-300 dark:border-[rgb(28,31,38)]">
          <div className="max-w-7xl mx-auto py-4 px-4 sm:px-6 lg:px-8">
            <div className="flex flex-col md:flex-row justify-center items-center space-y-4 md:space-y-0">
              <p className="text-sm text-gray-500 dark:text-gray-400 text-center">
                © {new Date().getFullYear()} 小铭Ai梦想家 版权所有 All rights reserved.
              </p>
            </div>
          </div>
        </div>
      </footer>

      {/* Google Analytics */}
      <Script
        src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GA_ID}`}
        strategy="afterInteractive"
      />
      <Script id="google-analytics" strategy="afterInteractive">
        {`
          window.dataLayer = window.dataLayer || [];
          function gtag(){dataLayer.push(arguments);}
          gtag('js', new Date());
          gtag('config', '${process.env.NEXT_PUBLIC_GA_ID}');
        `}
      </Script>

      {/* 百度统计 */}
      <Script strategy="afterInteractive">
        {`
          var _hmt = _hmt || [];
          (function() {
            var hm = document.createElement("script");
            hm.src = "https://hm.baidu.com/hm.js?YOUR_BAIDU_ANALYTICS_ID";
            var s = document.getElementsByTagName("script")[0]; 
            s.parentNode.insertBefore(hm, s);
          })();
        `}
      </Script>
    </div>
  );
} 